<!-- 验证码输入框-->
<template>
  <el-input
    v-model="data.captchaCode"
    placeholder="请输入验证码"
    @keyup.enter="handleSubmit"
  >
    <template #append>
      <el-image
        :src="captcha.captchaBase64"
        fit="cover"
        style="width: 120px; height: 32px"
        @click="onClinkCaptcha"
      />
    </template>
  </el-input>
</template>
<script lang="ts" setup>
//点击验证码图片
import { ElMessage } from "element-plus";
import { defineEmits, defineProps, onMounted, ref, watch } from "vue";
import { BasicControllerService, CaptchaVO } from "@/api";

interface CaptchaData {
  captchaKey: string;
  captchaCode: string;
}

/** 获取验证码 */
const captcha = ref<CaptchaVO>({}); //验证码对象
const data = ref<CaptchaData>({
  captchaCode: "",
  captchaKey: "",
});
const props = defineProps({
  timeLimitFlag: {
    type: Boolean,
    default: true,
  },
});

function getCaptcha() {
  BasicControllerService.getCodeUsingGet(props.timeLimitFlag).then((res) => {
    captcha.value.captchaBase64 = res.data?.captchaBase64;
    data.value.captchaKey = res.data?.captchaKey as string;
    ElMessage.success("获取验证码成功！");
  });
}

const timeCount = ref(0); //倒计时统计
const interval = ref(); // 计时器
function onClinkCaptcha() {
  if (timeCount.value === 0) {
    getCaptcha();
    interval.value = setInterval(() => {
      timeCount.value++;
      if (timeCount.value === 10) {
        timeCount.value = 0;
        clearInterval(interval.value);
      }
    }, 1000);
  } else {
    ElMessage.warning(`请${10 - timeCount.value}后再试`);
  }
}

const emit = defineEmits(["get:captcha:data"]);
watch(
  () => data.value.captchaCode,
  () => {
    emit("get:captcha:data", data.value);
  }
);

function handleSubmit() {
  emit("get:captcha:data", data.value, true);
}

onMounted(() => {
  getCaptcha();
});

onMounted(() => {
  clearInterval(interval.value);
});
</script>

<style scoped></style>
